import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';

import 'image_preview.dart';

class ImageWidget extends StatelessWidget {
  final String path;
  final bool isLocal;
  final BoxFit fit;
  final double? size;
  final double? radius;
  final bool? isPreview;
  final Function? onTap;
  final Widget? error;
  final bool? isCache;
  const ImageWidget({
    super.key,
    required this.path,
    this.isLocal = false,
    this.fit = BoxFit.cover,
    this.size,
    this.radius,
    this.isPreview,
    this.onTap,
    this.error,
    this.isCache = true,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: isPreview != true && onTap == null
          ? null
          : () {
              if (isPreview == true) {
                Get.to(() => ImagePreview(imageProvider: getImageProvider()));
              }
              if (onTap != null) {
                onTap!();
              }
            },
      child: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: radius != null
              ? BorderRadius.circular(radius!)
              : BorderRadius.circular(0),
        ),
        width: size,
        height: size,
        child: getImage(),
      ),
    );
  }

  ImageProvider<Object> getImageProvider() {
    if (isLocal) {
      return FileImage(File(path));
    }
    if (path.startsWith("http")) {
      return NetworkImage(path);
    }
    return AssetImage(path);
  }

  Widget getImage() {
    if (isLocal) {
      return Image.file(
        File(path),
        fit: fit,
      );
    }
    if (path.startsWith("http")) {
      String? uuid = isCache == false ? const Uuid().v4() : null;
      return CachedNetworkImage(
        cacheKey: uuid,
        imageUrl: path,
        progressIndicatorBuilder: (context, url, downloadProgress) {
          return CircularProgressIndicator(value: downloadProgress.progress);
        },
        errorWidget: (context, url, e) =>
            error ??
            Container(
              color: const Color.fromRGBO(1, 1, 0, 0.5),
              child: const Icon(Icons.error, color: Colors.white),
            ),
        fit: fit,
      );
    }
    return Image.asset(
      path,
      fit: fit,
    );
  }
}
